import { Component, OnInit } from '@angular/core';
import { NavController, Platform, LoadingController, AlertController } from '@ionic/angular';
import { HttpService } from 'src/app/service/http.service';
import { UrlService } from 'src/app/service/url.service';
import { ConfigService } from 'src/app/service/config.service';
import { InAppBrowser } from '@ionic-native/in-app-browser/ngx';
import { ToolService } from 'src/app/service/tool.service';
import { EventService } from 'src/app/service/event.service';
import { Storage } from '@ionic/storage';
import { PopwinService } from 'src/app/service/popwin.service';
import * as $ from 'jquery';
import { File } from '@ionic-native/file/ngx';
import { FileOpener } from '@ionic-native/file-opener/ngx';
import { FileTransfer,FileUploadOptions,FileTransferObject } from '@ionic-native/file-transfer/ngx';



@Component({
  selector: 'app-index',
  templateUrl: './index.page.html',
  styleUrls: ['./index.page.scss'],
})
export class IndexPage implements OnInit {
  menu = { "yhhd": 0, "jmhz": 0, "tjApp": 0, "cjwt": 0, "kjw": 0, "gz": 0, "grzx": 0 };
  public linkObj = { "online": "", "qq": "", "wximage": "", "lotUrl": "", "qqimage": "" };
  public money: any = 0;
  public showWin = false;
  public ewmStyleStr = "";//二维码类型
  public avatarImg: string;//用户的头像
  public isAvatar: boolean;//用户的头像
  public nickName: string = "";//昵称
  public isCordova: boolean = false;//是否是真机
  public fast = true;
  public isShowJoin=ConfigService.isAgent == 1?false:true;
  constructor(private navCtrl: NavController, private http: HttpService, private eventS: EventService, private store: Storage, private popWin: PopwinService,
    private iab: InAppBrowser,private platform:Platform,private file:File,private fileOpener:FileOpener,private transfer:FileTransfer,private loading:LoadingController,private alertCtrl:AlertController) { }

  ngOnInit() {
    this.initEvent();
    if (this.platform.is("cordova")) {
      this.isCordova = true;
    } else {
      this.isCordova = false;
    }
  }

  initEvent() {
    let that = this;
    this.eventS.subscribe("selectCommonTab1", function (index) {
      if (index == 1) {
        that.menuNet();
        that.userInfo();
        that.joinNet();
        that.isFastState();
        that.showTotalMoney();
      }
    }, true);
  }

  isFastState() {
    let isFast = localStorage.getItem("isFastMethod");
    if ((!ToolService.isEmpty(isFast) && isFast == '1' || ToolService.isEmpty(isFast))) {
      this.fast = true;
    } else {
      this.fast = false;
    }
  }
  menuNet() {
    //USER_MENU_MENU
    let that = this;
    this.http.get(UrlService.USER_MENU_MENU, { "callback": "JSONP_CALLBACK" }).subscribe(res => {
      let data = res.json();
      ToolService.setEncrypt(data.encrypt);
      if (data.code == ConfigService.SUCCESS_CODE) {
        that.menu = ToolService.aesDecodeToJson(data.data);
        // console.log(that.menu);
        //  that.lotRes = ToolService.aesDecodeToJson(data.data).data;
        // that.isLotRes=true;
      } else {
        //that.isLotRes=false;
      }
    }, error => {
      // this.popWin.toast(ToolService.newError(error));
    });
  }
  /**
   * 退出登录
   */
  onLoginOut() {
    this.store.remove("token");
    $("app-root").removeAttr("token");
    $("app-root").removeAttr("sessid");
    $("app-root").removeAttr("uid");
    this.store.clear();
    localStorage.clear();
    this.avatarImg = "";
    this.isAvatar = false;
    this.nickName = "";
    this.navCtrl.navigateRoot("/");
  }

  toPageFun(path: string) {
    this.navCtrl.navigateForward(path);
  }
  /**
   * 跳转到交易数据的页面
   */
  async  onWalletPage() {
    let that = this;
    await this.store.get(ConfigService.ROLE_KEY).then((data) => {
      if (data == '2') {
        that.popWin.toast("试玩账号不能进入");
        return;
      }
      that.toPageFun("/wallet");
    });
    // this.navCtrl.navigateForward("/transaction");
  }
  /**
   * 是否是测试账号
   */
  async isTestPlay() {
    let temp: any;
    await this.store.get(ConfigService.ROLE_KEY).then((data) => {
      temp = data;
    });
    if (temp == '2' || temp == 2) {
      return true;
    }
    return false;
  }
  /**
   * 优惠活动跳转
   */
  onPromotionPage() {
    this.toPageFun("/promotion");
  }
  /**
   * 加盟合作跳转
   */
  onJoinPage() {
    this.toPageFun("/join");
  }
  /**
   * 推荐APP跳转
   */
  onRecommendappPage() {
    if (ConfigService.isAgent == 1) {
      this.toPageFun("/recommendappagent");
    } else {
      this.toPageFun("/recommendapp");
    }

  }
  /**
   * 常见问题跳转
   */
  onConproPage() {
    this.toPageFun("/conpro");
  }
  /**
   * 跳转到意见反馈页面
   */
  onFkPage(){
    this.toPageFun("/fk");
  }
  /**
   * 跳转到反馈列表
   */
  onFkListPage(){
    this.toPageFun("/fklist");
  }
  /**
   * 规则跳转
   */
  onRulePage() {
    this.toPageFun("/rule");
  }
  /**
   * 开奖网跳转
   */
  onLotNetPage() {
    //168
    if (ToolService.isEmpty(this.linkObj.lotUrl)) {
      this.popWin.toast("暂无提供");
      return;
    } else {
      const browser = this.iab.create(this.linkObj.lotUrl, '_system');
    }
  }
  /**
   * 快速投注的切换
   */
  onFastBet() {
    let isFast = localStorage.getItem("isFastMethod");
    if ((!ToolService.isEmpty(isFast) && isFast == '1' || ToolService.isEmpty(isFast))) {
      localStorage.setItem("isFastMethod", "0");
      this.fast = false;
    } else {
      localStorage.setItem("isFastMethod", "1");
      this.fast = true;
    }
  }
  /**
   * 个人中心跳转
   */
  async  onPersonalCenterPage() {
    let that = this;
    await this.store.get(ConfigService.ROLE_KEY).then((data) => {
      if (data == '2') {
        that.popWin.toast("试玩账号不能进入");
        return;
      }
      that.toPageFun("/personalcenter");
    });

  }

  userInfo() {
    let that = this;
    this.store.get(ConfigService.USERINFO_KEY).then((data) => {
      let tempUserInfo = data;
      if (!ToolService.isEmpty(tempUserInfo)) {
        let userInfo = tempUserInfo;
        that.nickName = userInfo.uinfo.username;
        that.avatarImg = userInfo.uinfo.images;
        if (ToolService.isEmpty(that.avatarImg)) {
          that.isAvatar = false;
        } else {
          if (that.isTestPlay()) {
            that.isAvatar = false;
          } else {
            that.isAvatar = true;
          }
        }
      }
    });

  }

  async joinNet() {
    let linkData;
    let that = this;
    await this.store.get("linkmethod").then((data) => {
      linkData = data;
    });
    if (!ToolService.isEmpty(linkData)) {
      that.linkObj = linkData;
      return;
    }
    let obj = "{\"type\":\"" + "join" + "\"}";
    this.http.get(UrlService.OTHER_CONFIG, { "callback": "JSONP_CALLBACK", "data": ToolService.aesEncode(obj) }).subscribe(res => {
      let data = res.json();
      ToolService.setEncrypt(data.encrypt);
      if (data.code == ConfigService.SUCCESS_CODE) {
        let res = ToolService.aesDecodeToJson(data.data);
        that.linkObj = { "online": res.online.cfg_val, "qq": res.qq.cfg_val, "wximage": res.wximage.cfg_val, "lotUrl": res.lotteryweb.cfg_val, "qqimage": res.qqimage.cfg_val };
        that.store.set("linkmethod", that.linkObj);
      } else if (data.code == ConfigService.FAIL_CODE) {
        that.popWin.toast(data.message);
      } else if (data.code == ConfigService.LOGIN_CODE) {
        that.navCtrl.navigateForward("/login");
      }
    }, error => {
      console.log("error", error);
    });
  }
  /**
   * 客服系统
   */
  onLink(type, val) {
    if (type == "link") {
      if (ToolService.isEmpty(val)) {
        this.popWin.toast("暂无客服联系方式");
        return;
      } else {
        const browser = this.iab.create(val, '_system');
      }
    } else {
      if (ToolService.isEmpty(val)) {
        this.popWin.toast("暂无客服联系方式");
        return;
      }
      this.ewmStyleStr = type + "";
      this.showWin = true;
    }
  }

  hideWin() {
    this.showWin = false;
  }
  /**
   * 手动刷新余额
   */
  refreshMoney() {
    let that = this;
    this.http.get(UrlService.USER_FINDCREDIT, { "callback": "JSONP_CALLBACK" }).subscribe(res => {
      let data = res.json();
      ToolService.setEncrypt(data.encrypt);
      if (data.code == ConfigService.SUCCESS_CODE) {
        let res = ToolService.aesDecodeToJson(data.data);
        that.money = ToolService.keepTwoDecimal(res.credit2);
        that.store.set(ConfigService.MONEY_KEY, res);
      } else if (data.code == ConfigService.FAIL_CODE) {
        that.popWin.toast(data.message);
      } else if (data.code == ConfigService.LOGIN_CODE) {
        that.navCtrl.navigateForward("/login");
      }
    }, error => {
      console.log("error", error);
    });
  }

  /**
 * 获取资产并存储数据
 */
  async showTotalMoney() {
    let that = this;
    let tempMoney;
    await this.store.get(ConfigService.MONEY_KEY).then((data) => {
      tempMoney = data;
    });
    if (!ToolService.isEmpty(tempMoney)) {
      let temp = tempMoney;
      that.money = ToolService.keepTwoDecimal(temp.credit2);
      return;
    }
    that.refreshMoney();
  }

  /**
   * 下载的操作
   */

  onDownload(){
    let that = this;
    //agentVal的值 0非代理非第三方,1代理非第三方,2非代理第三方，3代理第三方
    let agentVal=0;
    if(ConfigService.isAgent==1){//代理
        if(ConfigService.is3rd){//第三方
          agentVal=3;
        }else{//非第三方
          agentVal=1;
        }
    }else{//非代理
        if(ConfigService.is3rd){
          agentVal=2;
        }else{
          agentVal=0;
        }
    }
    let obj = "{\"agent\":\"" + agentVal + "\",\"version_number\":\"" + ConfigService.APP_VERSION + "\"}";
    this.http.get(UrlService.USER_SYSTEMUPDATE, { "callback": "JSONP_CALLBACK", "data": ToolService.aesEncode(obj) }).subscribe(res => {
      let data = res.json();
      ToolService.setEncrypt(data.encrypt);
      if (data.code == ConfigService.SUCCESS_CODE) {
        let res = ToolService.aesDecodeToJson(data.data);
         console.log(res);
         if(ToolService.versionfunegt(res.version_number,ConfigService.APP_VERSION) && (res.is_forced==1 || res.is_forced=="1")){
            //强制更新
            that.presentAlertConfirm(res.update_content,true,res.plist_url,res.app_url);
         }else if(ToolService.versionfunegt(res.version_number,ConfigService.APP_VERSION) && (res.is_forced==0 || res.is_forced=="0")){
            //可以更新
            that.presentAlertConfirm(res.update_content,false,res.plist_url,res.app_url);
         }else if(!ToolService.versionfunegt(res.version_number,ConfigService.APP_VERSION)){
             that.presentMsgAlertConfirm();
         }
      } else if (data.code == ConfigService.FAIL_CODE) {
        that.popWin.toast(data.message);
      } else if (data.code == ConfigService.LOGIN_CODE) {
        that.navCtrl.navigateForward("/login");
      }
    }, error => {
      console.log("error", error);
    });

  }

  async presentMsgAlertConfirm(){
    const alert = await this.alertCtrl.create({
      header: '已更新到最新版本',
      message: "版本号:"+ConfigService.APP_VERSION,
      buttons: [
         {
          text: '关闭',
          handler: () => {
            
          }
        }
      ]
    });
    await alert.present();
  }

  async presentAlertConfirm(msg,isForce,iosUrl,androidUrl) {
    let that=this;
    if(isForce){
      const alert = await this.alertCtrl.create({
        header: '当前版本号:'+ConfigService.APP_VERSION,
        message: msg,
        buttons: [
           {
            text: '更新',
            handler: () => {
              that.downByUrl(iosUrl,androidUrl);
              return false;
            }
          }
        ]
      });
      await alert.present();
    }else{
      const alert = await this.alertCtrl.create({
        header: '当前版本号:'+ConfigService.APP_VERSION,
        message: msg,
        buttons: [
          {
            text: '取消',
            role: 'cancel',
            handler: (blah) => {
              
            }
          }, {
            text: '更新',
            handler: () => {
              that.downByUrl(iosUrl,androidUrl);
              return false;
            }
          }
        ]
      });
      await alert.present();
    }
   
  }



  downByUrl(iosUrl,androidUrl){
    if(this.platform.is("cordova") && this.platform.is("android")){
      this.downApk(androidUrl);
    }else if(this.platform.is("cordova") && this.platform.is("ios")){
      window.location.href=iosUrl;
      this.alertCtrl.dismiss();
      //const browser = this.iab.create("https://yll1024335892.github.io/yll_ipa/", '_system');
    }
  }

  async downApk(url){
    //"http://web.tw8999.com/android.apk"
    let that=this;
    const fileTransfer:FileTransferObject=this.transfer.create();
    let loadObj = await this.loading.create({
      message: '下载:0%',
      duration: 0
    });
    await loadObj.present();
    fileTransfer.download(url,this.file.externalDataDirectory+"wlh.apk").then((entry)=>{ 
        that.fileOpener.open(entry.toURL(),'application/vnd.android.package-archive').then((res)=>{
      },(e)=>{
         
      }).catch(e=>{
          
      });
    },(error)=>{
       
    });
    fileTransfer.onProgress((event:ProgressEvent)=>{
        let num=Math.ceil(event.loaded/event.total *100);
        if(num==100){
          loadObj.message="下载完成";
          console.log("完成");
          that.alertCtrl.dismiss();
        }else{
          loadObj.message="下载:"+num+"%";
          console.log("下载:"+num);
        }
    });



  }





}
